<?php
class Pageley_Basic_Domain_Money extends Pageley_Domain_AbstractCompositeValue {
    public function __construct($currency, $value) {
		$factory = Pageley_Config::getInstance();
        parent::__construct(new Pageley_Util_ArrayMap(array(
                "currency" => $currency,
                "value" => $value
            )), $factory->valueOf("attribute.money"));
    }

    public function add($money) {
        $result = null;
        $currency = $this->get("currency");
        if($currency != $money->get("currency")) {
            $money = $money->convert($currency);
        }
        $result = new Pageley_Basic_Domain_Money($currency, $this->get("value") + $money->get("value"));
        return $result;
    }

    public function subtract($money) {
        return $this->add($money->negative());
    }

    public function multiply($mutiplicand) {
        return new Pageley_Basic_Domain_Money($this->get("currency"), $multiplicand * $this->get("value"));
    }

    public function divide($divisor) {
        return $this->multiply(1 / $divisor);
    }

    public function convert($currency) {
        $exchangeRate = $this->findExchangeRate($this->get("currency"), $currency);
        return new Pageley_Basic_Domain_Money($currency, $exchangeRate * $this->get("value"));
    }

    private function findExchangeRate($currencyFrom, $currencyTo) {
        // TODO: make Currency a type, introduce ExchangeRate
        return 1;
    }

    public function negative() {
        return new Pageley_Basic_Domain_Money($this->get("currency"), -$this->get("value"));
    }

    public static function valueOf($properties) {
    	return new Pageley_Basic_Domain_Money(
    	   $properties->get("currency"),
    	   $properties->get("value"));
    }
    
    public function __toString() {
        return $this->get("currency") . " " . $this->get("value");
    }
}